import cv2 as cv
import numpy as np
import re

data = """0: [67.0118, 119.553], [109.682, 110.071], [122.647, 168.412], [79.9765, 177.894],
1: [209, 97], [212, 97], [212, 102], [209, 102],
2: [208.5, 99.5], [211, 97], [213.5, 99.5], [211, 102],
3: [3.25517, 58.6621], [28.5172, 36.2069], [52.4621, 63.1448], [27.2, 85.6],
4: [176.338, 47.6435], [200.693, 37.2794], [222.863, 89.3775], [198.507, 99.7417],"""

data = """0: [113.131, 108.472], [124.056, 166.455], [79.3386, 174.88], [68.414, 116.897],
1: [77.3911, 200.629], [77.3911, -41.5228], [100.554, -41.5228], [100.554, 200.629],
2: [208.968, 102.059], [208.968, 96.9412], [212.318, 96.9412], [212.318, 102.059],
3: [37.6567, 39.8028], [48.7467, 76.4445], [17.2412, 85.98], [6.15113, 49.3383],
4: [207.312, 32.938], [231.393, 84.8397], [199.836, 99.4817], [175.755, 47.5799],"""

number_re_str = r'-?\d+(?:\.\d+)?'
regexp = re.compile(rf'\[({number_re_str}), ({number_re_str})\]')

values = []
pos = 0
while True:
    numbers = regexp.search(data, pos)
    if numbers is None:
        break
    pos = numbers.end()
    values.append(float(numbers.group(1)))
    values.append(float(numbers.group(2)))

floats = np.array([float(num) for num in values], dtype=np.float32).reshape(-1, 4, 2)
print(floats)
M = len(floats)
print('M:', M)

W, H = 300, 223

canvas = np.zeros([H, W, 3], dtype=np.uint8)
canvas_idx = np.zeros_like(canvas, dtype=np.uint8)

for i in range(M):
    for j in range(4):
        cv.line(canvas, floats[i, j, :].astype(np.int0), floats[i, (j + 1)%4, :].astype(np.int0), (0, 255, 0), 1)

for i in range(M):
    for j in range(4):
        cv.putText(canvas_idx, f'{i}', floats[i, :, :].mean(axis=0).astype(np.int0), cv.FONT_HERSHEY_PLAIN, 1, (0, 255, 0), 1)

FACTOR = 4.
canvas = cv.resize(canvas, None, None, FACTOR, FACTOR, cv.INTER_CUBIC)
canvas_idx = cv.resize(canvas_idx, None, None, FACTOR, FACTOR, cv.INTER_CUBIC)

cv.imshow('rects', canvas)
cv.imshow('idx', canvas_idx)

cv.waitKey()
cv.destroyAllWindows()
